<template>
  <div class="flex-1 ml-4 bg-white rounded-lg shadow p-4 box-border">
    <div class="flex justify-between mb-5">
      <div class="text-base font-medium">Systems Statistics</div>
      <div class="text-sm text-gray-500">
        Latest: {{ getCurrentFormattedTime() }}
      </div>
    </div>

    <div class="grid grid-cols-2 grid-rows-2 gap-2 h-[calc(100%-36px)]">
      <!-- Solar Card -->
      <div
        class="bg-[#fffbf2] rounded-lg p-4 box-border border border-[#FFD591]"
      >
        <div class="flex items-center mb-3">
          <img :src="solar" alt="solar" class="w-6 h-6 mr-2" />
          <div class="text-base font-medium">Solar</div>
        </div>
        <div class="pt-2">
          <div class="text-xs text-gray-500 mb-1">Total Solar Generation</div>
          <div class="text-xl font-medium">
            {{ formatEnergy(statisticsData.solar.totalGeneration).value }}
            <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.solar.totalGeneration).unit }}</span>
          </div>
        </div>
      </div>

      <!-- Home Card -->
      <div
        class="bg-[#f1fbfe] rounded-lg p-4 box-border border border-[#91D5FF]"
      >
        <div class="flex items-center mb-3">
          <img :src="home" alt="home" class="w-6 h-6 mr-2" />
          <div class="text-base font-medium">Home</div>
        </div>
        <div class="pt-2">
          <div class="text-xs text-gray-500 mb-1">Total Consumption</div>
          <div class="text-xl font-medium">
            {{ formatEnergy(statisticsData.home.consumption).value }}
            <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.home.consumption).unit }}</span>
          </div>
        </div>
      </div>

      <!-- Grid Card -->
      <div
        class="bg-[#fcfbff] rounded-lg p-4 box-border border border-[#DDC4FB]"
      >
        <div class="flex items-center mb-3">
          <img :src="grid" alt="grid" class="w-6 h-6 mr-2" />
          <div class="text-base font-medium">Grid</div>
        </div>
        <div class="pt-2">
          <div class="flex">
            <div class="flex-1">
              <div class="text-xs text-gray-500 mb-1">Export to grid</div>
              <div class="text-xl font-medium truncate">
                {{ formatEnergy(statisticsData.grid.export).value }}
                <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.grid.export).unit }}</span>
              </div>
            </div>
            <div class="flex-1">
              <div class="text-xs text-gray-500 mb-1">Import from grid</div>
              <div class="text-xl font-medium truncate">
                {{ formatEnergy(statisticsData.grid.import).value }}
                <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.grid.import).unit }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Battery Card -->
      <div
        class="bg-[#f3fefb] rounded-lg p-4 box-border border border-[#80EACF]"
      >
        <div class="flex items-center mb-3">
          <img :src="battery" alt="battery" class="w-6 h-6 mr-2" />
          <div class="text-base font-medium">Battery</div>
        </div>
        <div class="pt-2">
          <div class="flex">
            <div class="flex-1">
              <div class="text-xs text-gray-500 mb-1">Charge to battery</div>
              <div class="text-xl font-medium truncate">
                {{ formatEnergy(statisticsData.battery.energyCharged).value }}
                <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.battery.energyCharged).unit }}</span>
              </div>
            </div>
            <div class="flex-1">
              <div class="text-xs text-gray-500 mb-1">Discharge from battery</div>
              <div class="text-xl font-medium truncate">
                {{ formatEnergy(statisticsData.battery.energyDischarged).value }}
                <span class="text-sm text-gray-400">{{ formatEnergy(statisticsData.battery.energyDischarged).unit }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, ref, onMounted, onUnmounted } from "vue";
import solar from "./assets/solar.png";
import home from "./assets/home.png";
import grid from "./assets/grid.png";
import battery from "./assets/battery.png";
import { formatTimeByUserTimezone, getTimezoneOffset } from "@/utils/timezone";

defineProps({
  statisticsData: {
    type: Object,
    required: true,
    default: () => ({
      updateTime: "",
      solar: { totalGeneration: 0 },
      home: { consumption: 0 },
      grid: { export: 0, import: 0 },
      battery: { energyCharged: 0, energyDischarged: 0 }
    })
  }
});

// 单位换算：0-9999 → kWh；10000-10000000 → MWh，均保留 2 位小数
const formatEnergy = (val: number | string) => {
  const num = Number(val) || 0;
  if (num < 10000) return { value: num.toFixed(2), unit: 'kWh' };
  return { value: (num / 1000).toFixed(2), unit: 'MWh' };
};

// 实时更新时间显示
let timeUpdateInterval: number | null = null;
const currentTime = ref(new Date());

// 获取当前格式化时间，格式：2025-02-12 19:20:25 (UTC+8:00)
const getCurrentFormattedTime = () => {
  try {
    // 使用响应式当前时间
    const timeToFormat = currentTime.value.toISOString();
    
    // 格式化时间：YYYY-MM-DD HH:mm:ss
    const formattedTime = formatTimeByUserTimezone(timeToFormat, 'datetime');
    const timezoneOffset = getTimezoneOffset();
    
    return `${formattedTime} (UTC${timezoneOffset})`;
  } catch (error) {
    console.error('格式化时间失败:', error);
    return 'No data';
  }
};

// 更新时间
const updateCurrentTime = () => {
  currentTime.value = new Date();
};

onMounted(() => {
  // 每1秒更新一次时间
  timeUpdateInterval = setInterval(updateCurrentTime, 1000);
});

onUnmounted(() => {
  if (timeUpdateInterval) {
    clearInterval(timeUpdateInterval);
  }
});
</script>
